const puppeteer = require('puppeteer')
const url = 'https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort=rank&page_limit=20&page_start=0';

const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

;
(async () => {
  console.log('爬数据')
  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    dumpio: false
  })
  const page = await browser.newPage();
  await page.goto(url, {
    waitUntil: 'networkidle2'
  })
  await sleep(3000)
  await page.waitForSelector('.more')
  for (let i = 0; i < 1; i++) {
    await sleep(3000)
    await page.click('.more')
  }
  const result = await page.evaluate(() => {
    var $ = window.$
    var items = $('.list > a')
    var movie_arr = []
    if (items.length >= 1) {
      items.each((index, item) => {
        let it = $(item)
        let detail_url = it.attr('href')
        let title = it.find('p').html()
        let rate = +it.find('p>strong').text()
        let id = it.find('.cover-wp').data('id')
        let img = it.find('.cover-wp > img').attr('src').replace('s_ratio', 'l_ratio')
        movie_arr.push({
          id,
          title,
          img,
          rate,
          detail_url
        })
      })
    }
    return movie_arr
  })
  browser.close()
  process.send({
    result
  })
  console.log(result)
  process.exit(0)
})()